#include "gameroom.h"
#include "gamehall.h"
#include "gameselect.h"

Gameroom::Gameroom(QWidget *parent) : QWidget(parent)
{
    this->setFixedSize(1200,900);
    this->setWindowIcon(QIcon(":res/ico.png"));
    this->setWindowTitle("贪吃蛇大作战");

    //初始化贪吃蛇
    snakeList.push_back(QRectF(this->width() * 0.5,this->height() * 0.5,ksnakeNodeWidth,ksnakeNodeHeight));
    moveUp();
    moveUp();

    //创建食物
    createNewFood();

    //定时器
    timer = new QTimer(this);
    connect(timer,&QTimer::timeout,[=](){
        int cnt = 1;

        if(snakeList.front().intersects(foodNode))
        {
            createNewFood();
            ++cnt;
            QSound::play(":res/eatfood.wav");
        }

        while(cnt--)
        {
            switch(moveDirect){
            case SnakeDirect::UP:
                moveUp();
                break;
            case SnakeDirect::DOWN:
                moveDown();
                break;
            case SnakeDirect::LEFT:
                moveLeft();
                break;
            case SnakeDirect::RIGHT:
                moveRight();
                break;
            default:
                qDebug() << "非法移动方向";
                break;
            }
        }

        snakeList.pop_back();
        update();

    });



    // 开始游戏  暂停游戏
    QFont font("方正舒体",20);
    QPushButton *strBtn = new QPushButton(this);
    QPushButton *stopBtn = new QPushButton(this);

    strBtn->move(1030,280);
    stopBtn->move(1030,340);

    strBtn->setFont(font);
    stopBtn->setFont(font);

    strBtn->setText("开始游戏");
    stopBtn->setText("暂停游戏");

    sound = new QSound(":res/Trepak.wav");
    // 信号槽
    connect(strBtn,&QPushButton::clicked,[=](){
        //sound = new QSound(":res/Trepak.wav");
        sound->play();
        sound->setLoops(-1);

        isGameStart = true;
        timer->start(moveTimeout);

        qDebug() << " 游戏正常运行 ";

    });

    connect(stopBtn,&QPushButton::clicked,[=](){
        QSound::play(":res/clicked.wav");
        isGameStart = false;
        timer->stop();
        sound->stop();
        qDebug() << " 游戏暂停 ";
    });

    // 方向控制键
    QFont dfont("方正舒体",40);
    QPushButton *up = new QPushButton(this);
    QPushButton *down = new QPushButton(this);
    QPushButton *left = new QPushButton(this);
    QPushButton *right = new QPushButton(this);

    up->move(1070,470);
    down->move(1070,570);
    left->move(1030,520);
    right->move(1110,520);

    up->setFont(dfont);
    down->setFont(dfont);
    left->setFont(dfont);
    right->setFont(dfont);

    up->setText("↑");
    down->setText("↓");
    left->setText("←");
    right->setText("→");

    up->setStyleSheet("QPushButton{border:0px;}");
    down->setStyleSheet("QPushButton{border:0px;}");
    left->setStyleSheet("QPushButton{border:0px;}");
    right->setStyleSheet("QPushButton{border:0px;}");

    // 信号槽
    connect(up,&QPushButton::clicked,[=](){
        if(moveDirect != SnakeDirect::DOWN)
            moveDirect = SnakeDirect::UP;
    });
    connect(down,&QPushButton::clicked,[=](){
        if(moveDirect != SnakeDirect::UP)
            moveDirect = SnakeDirect::DOWN;
    });
    connect(left,&QPushButton::clicked,[=](){
        if(moveDirect != SnakeDirect::RIGHT)
            moveDirect = SnakeDirect::LEFT;
    });
    connect(right,&QPushButton::clicked,[=](){
        if(moveDirect != SnakeDirect::LEFT)
            moveDirect = SnakeDirect::RIGHT;
    });

    // 退出游戏键
    QPushButton *exitBtn = new QPushButton(this);
    exitBtn->move(1030,800);
    exitBtn->setFont(font);
    exitBtn->setText("退出游戏");

    QMessageBox *msg = new QMessageBox(this);
    //msg->setWindowIcon(QIcon(":res/ico.png"));
    msg->setIcon(QMessageBox::Question);
    msg->setWindowTitle("退出游戏");
    msg->setText("是否退出游戏，返回上一界面？");

    QPushButton *ok = new QPushButton("ok");
    QPushButton *cancel = new QPushButton("cancel");

    msg->addButton(ok,QMessageBox::AcceptRole);
    msg->addButton(cancel,QMessageBox::RejectRole);

    connect(exitBtn,&QPushButton::clicked,[=](){
        QSound::play(":res/clicked.wav");
        // 弹出一个对话框
        msg->show();
        msg->exec();

        if(msg->clickedButton() == ok)
        {
            this->close();
            GameSelect *select = new GameSelect;
            select->show();
            select->setGeometry(this->geometry());
            QSound::play(":res/clicked.wav");
            qDebug() << " 退出游戏，返回上一界面 ";
            sound->stop();
            qDebug() << " 停止背景音乐 ";
        }
        else
        {
            QSound::play(":res/clicked.wav");
            qDebug() << " 返回 ";
            msg->close();
        }
    });
}

void Gameroom::paintEvent(QPaintEvent *event)
{
    QPainter painter(this);
    QPixmap pix;

    //左侧草地
    if(styleRoom == GameStyle::SIMPLE)
    {
        pix.load(":res/simple_room.png");
    }
    else if(styleRoom == GameStyle::NORMAL)
    {
        pix.load(":res/normal_room.png");
    }
    else if(styleRoom == GameStyle::COMPLEX)
    {
        pix.load(":res/hard_room.png");
    }
    painter.drawPixmap(0,0,1000,900,pix);

    //右侧控制台
    pix.load(":res/bg1.png");
    painter.drawPixmap(1000,0,200,1000,pix);

    //绘制蛇
    // 蛇头
    if(moveDirect == SnakeDirect::UP)
    {
        pix.load(":res/up.png");
    }
    else if(moveDirect == SnakeDirect::DOWN)
    {
        pix.load(":res/down.png");
    }
    else if(moveDirect == SnakeDirect::LEFT)
    {
        pix.load(":res/left.png");
    }
    else if(moveDirect == SnakeDirect::RIGHT)
    {
        pix.load(":res/right.png");
    }
    auto snakeHead = snakeList.front();
    painter.drawPixmap(snakeHead.x(),snakeHead.y(),snakeHead.width(),snakeHead.height(),pix);


    // 蛇身
    pix.load(":res/Bd.png");
    for(int i = 1; i < snakeList.size() - 1; i++)
    {
        auto node = snakeList.at(i);
        painter.drawPixmap(node.x(),node.y(),node.width(),node.height(),pix);
    }

    // 蛇尾
    auto snakeTail = snakeList.back();
    painter.drawPixmap(snakeTail.x(),snakeTail.y(),snakeTail.width(),snakeTail.height(),pix);

    //绘制食物
    if(styleRoom == GameStyle::SIMPLE)
    {
        pix.load(":res/simple_food.png");
    }
    else if(styleRoom == GameStyle::NORMAL)
    {
        pix.load(":res/normal_food.bmp");
    }
    else if(styleRoom == GameStyle::COMPLEX)
    {
        pix.load(":res/hard_food.png");
    }
    painter.drawPixmap(foodNode.x(),foodNode.y(),foodNode.width(),foodNode.height(),pix);


    // 绘制分数
    pix.load(":res/sorce_bg.png");
    painter.drawPixmap(1050,100,100,50,pix);
//    pix.load(":res/scores.png");
//    painter.drawPixmap(1050,102,50,40,pix);

    QPen pen;
    pen.setColor(Qt::black);
    painter.setPen(pen);
    QFont qfont("楷体",30);
    painter.setFont(qfont);
    painter.drawText(this->width() * 0.92, this->height() * 0.16,
                        QString("%1").arg(snakeList.size()));

    // 积分写入历史战绩中
    QFile file("D:/SHIMIR/Documents/SnakesGame/history.txt");

    int c = snakeList.size();
    if(file.open(QIODevice::WriteOnly | QIODevice::ReadWrite))
    {
        QTextStream out(&file);
        int num = c - 3;
        out << num;

        file.close();
    }

    //绘制游戏失败效果
    if(checkFail())
    {
        pen.setColor(Qt::red);
        painter.setFont(qfont);
        painter.setPen(pen);
        painter.drawText(this->width() * 0.4,this->height() * 0.5,QString("GAME OVER!"));
        timer->stop();
        QSound::play(":res/gameover.wav");

        qDebug() << sound;
        qDebug() << " gameover!!!1 ";
        sound->stop();
    }
}

bool Gameroom::checkFail()
{

    for(int i = 0; i < snakeList.size(); i++)
    {
        for(int j = i + 1; j <snakeList.size(); j++)
        {
            if(snakeList.at(i) == snakeList.at(j))
            {
                qDebug() << "游戏检测失败";
                return true;
            }
        }
    }
    return false;

}

void Gameroom::moveUp()
{
    QPointF leftTop;
    QPointF rightBottom;

    auto snakeHead = snakeList.front();
    int headX = snakeHead.x();
    int headY = snakeHead.y();

    if(headY < ksnakeNodeHeight)
    {
        leftTop = QPointF(headX,this->height() - ksnakeNodeHeight);
    }
    else
    {
        leftTop = QPointF(headX,headY - ksnakeNodeHeight);
    }
    rightBottom = leftTop + QPointF(ksnakeNodeWidth,ksnakeNodeHeight);

    snakeList.push_front(QRectF(leftTop,rightBottom));
}

void Gameroom::moveDown()
{
    QPointF leftTop;
    QPointF rightBottom;

    auto snakeHead = snakeList.front();
    int headX = snakeHead.x();
    int headY = snakeHead.y();

    if(headY + ksnakeNodeHeight * 2 > this->height())
    {
        leftTop = QPointF(headX,0);
    }
    else
    {
        //leftTop = QPointF(headX,headY + ksnakeNodeHeight);
        leftTop = snakeHead.bottomLeft();
    }
    rightBottom = leftTop + QPointF(ksnakeNodeWidth,ksnakeNodeHeight);
    snakeList.push_front(QRectF(leftTop,rightBottom));
}

void Gameroom::moveLeft()
{
    QPointF leftTop;
    QPointF rightBottom;

    auto snakeHead = snakeList.front();
    int headX = snakeHead.x();
    int headY = snakeHead.y();

    if(headX - ksnakeNodeWidth < 0)
    {
        leftTop = QPointF(1000 - ksnakeNodeWidth,headY);
    }
    else
    {
        leftTop = QPointF(headX - ksnakeNodeWidth,headY);

    }
    rightBottom = leftTop + QPointF(ksnakeNodeWidth,ksnakeNodeHeight);
    snakeList.push_front(QRectF(leftTop,rightBottom));
}

void Gameroom::moveRight()
{
    QPointF leftTop;
    QPointF rightBottom;

    auto snakeHead = snakeList.front();
    int headX = snakeHead.x();
    int headY = snakeHead.y();

    if(headX + ksnakeNodeWidth > 980)
    {
        leftTop = QPointF(0,headY);
    }
    else
    {
        //leftTop = QPointF(headX,headY + ksnakeNodeHeight);
        leftTop = snakeHead.topRight();
    }
    rightBottom = leftTop + QPointF(ksnakeNodeWidth,ksnakeNodeHeight);
    snakeList.push_front(QRectF(leftTop,rightBottom));
}

void Gameroom::createNewFood()
{
    foodNode = QRectF(qrand() % (1000/ksnakeNodeWidth) * ksnakeNodeWidth,
                      qrand() % (this->height()/ksnakeNodeHeight) * ksnakeNodeHeight,
                      ksnakeNodeWidth,
                      ksnakeNodeHeight);
}
